<?php
namespace Endpoints\CandyContent;

use Carbon\Carbon;
use Endpoints\Base\Endpoint;
use Endpoints\Tools\GetOssObject;
use Endpoints\Tools\UploadOssObject;
use Models\Candy\Calendar;
use Models\Candy\Content;
use Repositories\Candy\CalendarRepository;
use Repositories\Candy\ContentRepository;
use Symfony\Component\Console\Input\InputArgument;

class CreateContent extends Endpoint
{
    // 定义参数
    const ARGUMENT_FILES  = 'files';
    const ARGUMENT_SAVE_DATE  = 'save_date';
    const ARGUMENT_IS_PRIVATE = 'is_private';
    const ARGUMENT_TITLE = 'title';
    const ARGUMENT_INTRO = 'intro';
    const ARGUMENT_DESCRIPTION = 'description';
    const ARGUMENT_SORT = 'sort';

    // 收参
    public function getArguments()
    {
        return [
            [static::ARGUMENT_FILES,InputArgument::REQUIRED,'文件',''],
            [static::ARGUMENT_SORT,InputArgument::OPTIONAL,'排序',0],
            [static::ARGUMENT_SAVE_DATE,InputArgument::OPTIONAL,'日期',date("Y-m-d")],
            [static::ARGUMENT_IS_PRIVATE,InputArgument::OPTIONAL,'是否隐私',0],
            [static::ARGUMENT_TITLE,InputArgument::OPTIONAL,'图片标题',''],
            [static::ARGUMENT_DESCRIPTION,InputArgument::OPTIONAL,'图片描述',''],
            [static::ARGUMENT_INTRO,InputArgument::OPTIONAL,'当日描述',''],
        ];
    }

    /**
     * @return mixed
     * @throws \Laravelladder\Core\Exceptions\Endpoints\ArgumentRequiredException
     * @throws \Laravelladder\Core\Exceptions\Validations\ValidationException
     */
    public function dryRun()
    {
        $strFiles    = $this->argument(static::ARGUMENT_FILES);
        $sort        = $this->argument(static::ARGUMENT_SORT);
        $saveDate    = $this->argument(static::ARGUMENT_SAVE_DATE);
        $title       = $this->argument(static::ARGUMENT_TITLE);
        $description = $this->argument(static::ARGUMENT_DESCRIPTION);
        $isPrivate   = $this->argument(static::ARGUMENT_IS_PRIVATE);
        $intro       = $this->argument(static::ARGUMENT_INTRO);
        $dateObj = new Carbon($saveDate);
        $saveYear    = $dateObj->year;
        $saveMonth   = ($dateObj->month < 10) ? '0'.$dateObj->month : $dateObj->month;
        $saveDay     = $dateObj->day;
        $date        = $saveYear.'-'.$saveMonth.'-'.$saveDay;
        // 检测日期并创建
        $calendarItem = CalendarRepository::getInstance()->getOneByFieldValue(Calendar::DB_FIELD_DATE,$date);
        if(!$calendarItem){
            $calendarItem = CalendarRepository::getInstance()->insertAndGetModel([
                Calendar::DB_FIELD_DATE => $date,
                Calendar::DB_FIELD_INTRO => $intro,
            ]);
        }else{
            if(!empty($calendarItem->{Calendar::DB_FIELD_INTRO})){
                CalendarRepository::getInstance()->updateById($calendarItem->getKey(),[
                    Calendar::DB_FIELD_INTRO => $intro,
                ]);
            }
        }
        $dateId = $calendarItem->getKey();
        // 计算10s前已有的图片数量
        $existsRes = ContentRepository::getInstance()->getListByFilters([
            ['date_id','=',$dateId],['created_at','<',date("Y-m-d H:i:s",time()-30)]
        ],1,0);

        foreach ($strFiles as $index=>$strFile){
            $fileName = time().rand(100,9999).rand(500,999). '.jpg';
            $filePath = "/tmp/".$fileName;
            $calcSort = $existsRes->paginator_total*10+$sort;
            \Log::debug("图片_sort值{$sort}_总数{$existsRes->paginator_total}_计算sort值_{$calcSort}_{$fileName}");
            file_put_contents($filePath,base64_decode($strFile));
            $objName     = UploadOssObject::getInstance()->setArguments([
                UploadOssObject::ARGUMENT_FILE_NAME  => $fileName,
                UploadOssObject::ARGUMENT_FILE_PATH  => $filePath,
                UploadOssObject::ARGUMENT_SAVE_YEAR  => $saveYear,
                UploadOssObject::ARGUMENT_SAVE_MONTH => $saveMonth,
                UploadOssObject::ARGUMENT_SAVE_DAY   => $saveDay,
            ])->dryRun();
            unlink($filePath);
            if($objName){
                $model[] = ContentRepository::getInstance()->insertAndGetModel([
                    Content::DB_FIELD_TITLE       => $title,
                    Content::DB_FIELD_FILE_VALUE  => $objName,
                    Content::DB_FIELD_DESCRIPTION => $description,
                    Content::DB_FIELD_IS_PRIVATE  => $isPrivate,
                    Content::DB_FIELD_DATE_ID     => $dateId,
                    Content::DB_FIELD_SORT        => $calcSort,
                ]);
            }
        }
        return $model;
    }
}